const seturl = "https://localhost:8000";

let urlString = window.location.href.split('/');
let id = urlString[urlString.length - 1] * 1;

function btnSave() {

    form.addEventListener("submit", (e) => {
        e.preventDefault();        // 阻止默认行为

        let arr = document.querySelectorAll('.form-group');
        let lll1 = document.querySelector('.form-group');
        console.log(lll1.id);
        
        let userObj = {};
        arr.map((item) => { userObj[item.id] = item.value })

        console.log(userObj);

        if (!id) {
            // Add
            fetch(`${seturl}/users`, {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(userObj),
            }).then((response) => response.json())
                .then((userObj) => {
                    console.log("Success:", userObj);
                })
                .catch((error) => {
                    console.error("Error:", error);
                });

        } else {

            //Update
            fetch(`${seturl}/users/${id}`, {
                method: "PUT",
                headers: {
                    "Content-Type": "application/json",

                },
                body: JSON.stringify(userObj)
            }).then((response) => response.json())
                .then((userObj) => {
                    console.log("Success:", userObj);
                })
                .catch((error) => {
                    console.error("Error:", error);
                });

            // document.addEventListener("DOMContentLoaded", function () {

            //     let registratioName = document.querySelector("#name");
            //     let registrationAge = document.querySelector("#age");
            //     let registrationEmail = document.querySelector("#email");
            //     let registrationGender = document.querySelector("#gender");

            //     registratioName.value = user


            // });
        }
    })

}

// RegistrationTimeInput
window.addEventListener("DOMContentLoaded", function () {
    let registrationTimeInput = document.querySelector("#registrationTime");
    let now = new Date();

    const utcDate = new Date(now.toISOString());
    const beijingTime = new Date(utcDate.getTime() + 8 * 60 * 60 * 1000);   // 加 8 小时

    // console.log(beijingTime.toISOString().slice(0, 16).replace('T', ' '));
    const newtime = beijingTime.toISOString().slice(0, 16).replace('T', ' ');
    // console.log(now.toISOString().slice(0, 16));
    // console.log(now.toLocaleString());

    registrationTimeInput.value = newtime;
});